<template>
  <div class="serach-data">
    <div class="content">
      <div class="collected-block">
        <el-card class="card">
          <label>数据查询</label>
          <el-row v-loading="!!callbackCount">
            <el-col class="part" :span="12">
              <br><br>
              <el-form :model="ruleForm" ref="ruleForm" :rules="rules" label-width="80px">
                <el-form-item prop="boxMac" label="盒子设备">
                  <el-select v-model="ruleForm.boxMac" filterable placeholder="请选择盒子Mac">
                    <el-option
                      v-for="item in boxList"
                      :key="item.mac"
                      :label="item.mac"
                      :value="item.mac">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="targetMac" label="目标设备">
                  <el-input style="width:218px;" v-model="ruleForm.targetMac"
                            placeholder="输入被采集的Mac">
                  </el-input>
                </el-form-item>
                <el-form-item>
                  <el-button class="submit-btn" type="primary" @click="handleSubmit('ruleForm')">查询</el-button>
                </el-form-item>

              </el-form>
            </el-col>
            <el-col :span="12">
              <div class="info-bar">

                <p class="line"><span class="title">采集设备:</span><span class="value">{{(callbackCount === 0) ?  dataShow(chip) : ''}}</span>
                </p>
                <p class="line"><span class="title">目标Mac:</span><span class="value">{{(callbackCount === 0) ?  dataShow(mac) : ''}}</span>
                </p>
                <p class="line"><span class="title">采集距离:</span><span class="value">{{(callbackCount === 0) ?  dataShow(distance) :''}}</span>
                </p>
                <p class="line"><span class="title">采集时间:</span><span class="value">{{(callbackCount === 0) ?  dataShow(time) :''}}</span>
                </p>
                <p class="line"><span class="title">广告追踪:</span><span class="value">{{(callbackCount === 0) ?  dataShow(traceId) :''}}</span>
                  <span v-show="traceId" class="operation">
                    <el-button @click="requestAdPusher(traceId)" size="small" type="primary">精准投递</el-button>
                  </span>
                </p>
              </div>
            </el-col>
          </el-row>

        </el-card>
      </div>
      <div class="btn-list" v-show="searchMac">
        <el-button style="margin-left:10px;" @click="$router.push('/ad')" type="primary">精准广告投递</el-button>
        <el-button @click="handleNext" type="primary">已获得用户授权查看个人画像</el-button>
      </div>
    </div>
    <el-dialog title="最新数据" :visible="false" width="500px">
      <div class="center">
        <el-form label-width="80px">
          <el-form-item label="采集设备:">
            <span class="val">{{chip}}</span>
          </el-form-item>
          <el-form-item label="目标MAC:">
            <span class="val">{{mac}}</span>
          </el-form-item>
          <el-form-item label="采集距离:">
            <span class="val">{{distance}}</span>
          </el-form-item>
          <el-form-item label="采集时间:">
            <span class="val">{{time}}</span>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {normalGet, normalPost} from "../../methods2";
  import {transChineseDate} from "../../methods2/util";

  let remoteHost = 'http://api.gdyunlifang.com',
      localHost = '',
      host = remoteHost,
      queryInfoUrl = host + '/data/latest/info/',
      boxListUrl = host +'/device/list/whole',

      adTraceUrl = host + '/ids/',

      submitUrl = {
        md5: host + '/ad/append/imei/md5/',
        imei: host + '/ad/append/imei/',
        idfa: host + '/ad/append/idfa/',
      };

  export default {
    name: "search-data",
    data() {
      var checkMac1 = (rule, value, callback) => {
          if (value === '') {
            callback(new Error('请输入MAC'));
          } else if (!this.sa.checkMac(this.ruleForm.targetMac.trim())) {
            callback(new Error('请参考 [ aa:aa:aa:aa:aa:aa ]'));
          } else {
            callback();
          }

        },
        checkMac2 = (rule, value, callback) => {
          if (value === '') {
            callback(new Error('请输入MAC'));
          } else if (!this.sa.checkMac(this.ruleForm.boxMac.trim())) {
            callback(new Error('请参考 [ aa:aa:aa:aa:aa:aa ]'));
          } else {
            callback();
          }
          ;
        }
      return {
        chip: this.$root.chip,
        mac: this.$root.mac,
        distance: this.$root.distance,
        time: this.$root.time,
        traceId: this.$root.traceId,
        searchMac: this.$root.searchMac,
        data: [],
        callbackCount: 0,
        boxList:'',
        ruleForm: {
          boxMac: '',
          targetMac: '',
        },
        rules: {
          targetMac: [
            {required: true, message: 'Mac 不能为空', trigger: 'blur'},
            {validator: checkMac1, trigger: 'change'},
            {validator: checkMac1, trigger: 'blur'},
          ],
          boxMac: [
            {required: true, message: 'Mac 不能为空', trigger: 'change'},
            {validator: checkMac2, trigger: 'change'},
            {validator: checkMac2, trigger: 'blur'},
          ]
        },
      }

    },
    mounted(){
      this.requestBoxList();
    },
    computed:{
      _distance(){
        return this.traceId ? this.distance : ' ';  //非空字符 ， 作为dataShow 的判断
      },
      _time(){
        return  this.traceId ? this.time : ( this.mac ? transChineseDate(Date.now()) : '暂无数据');  //判断time的显示，以及请求盒子列表后的显示
      }
    },
    methods: {
      clearLoading() {
        console.log(this.distance)
        this.callbackCount--;


      },
      dataShow(v) {
        return v || '暂无数据';
      },
      handleReset() {
        this.ruleForm.boxMac = '';
        this.ruleForm.targetMac = '';
      },
      handleSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let mac = this.ruleForm.targetMac.trim().replace(/：/g, ':');
            this.requestInfo(mac);
          } else {
            this.$message.warning('MAC 地址输入不正确，请参考 [ aa:aa:aa:aa:aa:aa ]');
          }
        });
      },
      handleNext() {
        this.$router.push({name: 'portrait', params: {mac: this.searchMac}});
      },
      requestBoxList(){
        let suc = (data) => {
              this.boxList = data;
            },
            err = () => {
              this.$message.warning('请求盒子列表失败，可能是网络有过高的延时...');
            };

        this.callbackCount = 1;
        normalGet(boxListUrl,'',suc,err,this.$message,this.clearLoading);
      },
      requestAdPusher(traceId) {
        let type,
          suc = (data) => {
            this.$message.success('广告推送成功')
          },
          err = () => {
            this.$message.warning('广告推送失败，可能是网络有过高的延时...');
          };

        if (traceId.indexOf('-') !== -1) {
          type = 'idfa';
        } else if (traceId.length === 32) {
          type = 'md5';
        } else {
          type = 'imei';
        }
        this.callbackCount = 1;
        normalGet(submitUrl[type] + traceId, '', suc, err, this.$message, this.clearLoading);
      },

      requestInfo(mac) {
        if(!this.ruleForm.boxMac || !mac){
          this.$message.warning('必须输入盒子设备和目标设备的MAC ！');
          return ;
        }
        this.callbackCount = 2;
        this.requestDeviceInfo(this.ruleForm.boxMac,mac);
        this.requestAdTrace(mac);

      },
      requestDeviceInfo(boxMac,mac) {
        let suc = (data) => {
              if (!data.chip) {
                this.$message.warning('没有查到相关数据...');
                this.$root.chip = this.chip = '';
                this.$root.mac = this.mac = '';
                this.$root.searchMac = this.searchMac = '';
                this.$root.distance = this.distance = '';
                this.$root.time = this.time = ' ';

                return;
              }

              this.$root.chip = this.chip = data.chip;
              this.$root.mac = this.mac = data.mac;
              this.$root.searchMac = this.searchMac = data.mac;
              this.$root.distance = this.distance = data.distance + ' 米';
              this.$root.time = this.time = transChineseDate(data.time * 1000);
            },
            err = () =>{
              this.$message.warning('请求失败，请检查网络');
            }

        normalGet(queryInfoUrl + '/' + boxMac + '/' + mac, '', suc, err, this.$message, this.clearLoading);
      },
      requestAdTrace(mac) {
        let suc = (data) => {
              this.$root.traceId = this.traceId = data.imeimd5 || data.idfa || data.imei || '';
            },
            err = () => {
              this.$message.warning('请求广告追踪码失败，可能是网络有过高的延时...');
            };


        normalGet(adTraceUrl + mac, '', suc, err, this.$message, this.clearLoading);
      }
    },
  }
</script>

<style scoped lang="scss">
  @import '../../static/style/public';

  hr {
    border-color: $lightGrey;
  }

  label {
    color: #202326;
    font-weight: 400;

  }

  .center {
    @include flexCenter;
  }

  .serach-data {
    .content {

      color: $lightGrey;
      margin-top: $breadCrumbMargin;
      .bottom-block {
        margin: 10px 0px;
      }
      .card {
        padding: 20px;
      }
      .part {
        padding-right: 80px;
      }

      .collected {
        .val {
          padding: 0 20px;
          font-size: 15px;
        }
      }
      .btn-list {
        padding: 30px;
        @include flexCenter;
      }

      .line {
        .title {
          font-size: 18px;
          font-weight: 550;
        }
        .value {
          padding-left: 40px;
          font-size: 16px;
          font-weight: 550;
        }
        .operation {
          padding: 0 10px;
        }
      }

    }
  }
</style>
